package controller;

import java.io.IOException;
import java.util.ArrayList;

import model.User;

import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Fileupload;
import org.zkoss.zul.Image;
import org.zkoss.zul.Textbox;

import util.FileUtils;

import admin.dao.UserDAO;

public class AddUserCtrl extends SelectorComposer<Component>{
	private static final long serialVersionUID = 1L;

	@Wire
    private Textbox txUsername;
	
	@Wire
    private Textbox txPassword;
	
	@Wire
    private Textbox txRePassword;
	
	@Wire
    private Textbox txEmail;
	
	@Wire
    private Image imgAvatar;
	
	private String avatarPath;
	private ArrayList<String> errorMessages;
	
	
	@Listen("onUpload = #btUpload")
    public void upload(UploadEvent event){
		Media media = event.getMedia();
		imgAvatar.setContent((org.zkoss.image.Image) media);
		try {
			avatarPath = FileUtils.saveFileFromMedia(media, null,"member");
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
	
	@Listen("onClick = #btSubmit")
    public void submit(){
		errorMessages = new ArrayList<String>();
		if(this.validated()) {
			UserDAO.registerUser(new User(txUsername.getValue(), txPassword.getValue(), txEmail.getValue(), avatarPath));
			Executions.getCurrent().sendRedirect("user_view_layout.jsp");
		} else {
			String error = "";
			for (String message : errorMessages) {
				error += message + "\n";
			}
			Clients.showNotification(error, "error", null, "middle_center", 3000);
		}
    }

	private boolean validated() {
		if (!UserDAO.checNewUsername(txUsername.getValue(), 0)) {
			errorMessages.add("Username conflict.");
		}
		if (!txPassword.getValue().equals(txRePassword.getValue())) {
			errorMessages.add("Password missmatch.");
		} 
		
		return errorMessages.size() == 0;
	}
}
